package com.pig.controller;

import com.pig.entity.Category;
import com.pig.service.CategoryService;
import com.pig.dto.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类控制器
 */
@RestController
@RequestMapping("/category")
@Tag(name = "分类管理", description = "商品分类相关接口")
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询分类")
    public Result<Category> getCategoryById(@PathVariable Long id) {
        try {
            Category category = categoryService.getCategoryById(id);
            return Result.success(category);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/list")
    @Operation(summary = "查询所有分类")
    public Result<List<Category>> getAllCategories() {
        try {
            List<Category> categories = categoryService.getAllCategories();
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/parent/{parentId}")
    @Operation(summary = "根据父分类ID查询子分类")
    public Result<List<Category>> getCategoriesByParentId(@PathVariable Long parentId) {
        try {
            List<Category> categories = categoryService.getCategoriesByParentId(parentId);
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping
    @Operation(summary = "添加分类")
    public Result<Category> addCategory(@RequestBody Category category) {
        try {
            Category newCategory = categoryService.addCategory(category);
            return Result.success(newCategory);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @PutMapping
    @Operation(summary = "更新分类")
    public Result<Category> updateCategory(@RequestBody Category category) {
        try {
            Category updatedCategory = categoryService.updateCategory(category);
            return Result.success(updatedCategory);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "删除分类")
    public Result<Boolean> deleteCategory(@PathVariable Long id) {
        try {
            boolean result = categoryService.deleteCategory(id);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
} 